/* eslint-disable react-hooks/exhaustive-deps */
import React, { useState, useEffect, useRef } from 'react';
import { Table, Spin, message, Space, Popconfirm, Button, Tag } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import css from './index.less';
import { menuList, update } from './api';
import EditForm from './EditForm';
import AddForm from './AddForm';
import { PlusOutlined } from '@ant-design/icons';
import { stateColors } from '@/utils/variable';

/**
 * 系统管理/权限管理/菜单管理
 */
const SuperTable: React.FC<{
  dataSource: MenuAPI.DataType[];
  // pagination: any;
  menus: any;
  infoUpdate: any;
}> = ({
  dataSource,
  // pagination,
  menus,
  infoUpdate,
}) => {
  const editRef = useRef<any>(false);

  //编辑
  const updateHandle = async (record: MenuAPI.DataType) => {
    editRef.current.setEditData(record);
    const menusList = menus.filter((item: any) => item.key != record?.id);
    editRef.current.setMenus(menusList);
    editRef.current.setVis({ open: true, id: record.id });
  };

  // 启用禁用状态修改
  const statusHandle = async (record: MenuAPI.DataType) => {
    if (record) {
      const status = record.status === 0 ? 1 : 0;
      const data = { ...record, status: status };
      const res = await update(data);
      if (res.code === 200) {
        message.success(res.msg);
        infoUpdate(true);
      } else {
        message.error(res.msg);
      }
    }
  };

  const columns: ColumnsType<MenuAPI.DataType> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      ellipsis: true,
      width: 150,
    },
    {
      title: '路径',
      dataIndex: 'path',
      key: 'path',
      align: 'center',
      ellipsis: true,
      width: 150,
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      align: 'center',
      ellipsis: true,
      width: 80,
      render: (value: number) => {
        return <>{value === 1 ? '菜单' : '按钮'}</>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      width: 80,
      render: (value: number) => {
        return (
          <>
            {value === 0 ? (
              <Tag color={stateColors[0]}>禁用</Tag>
            ) : (
              <Tag color={stateColors[1]}>启用</Tag>
            )}
          </>
        );
      },
    },
    {
      title: '操作',
      align: 'center',
      key: 'action',
      ellipsis: true,
      fixed: 'right',
      width: 120,
      render: (_, record) => {
        return (
          <Space size="middle">
            <a onClick={() => updateHandle(record)}>编辑</a>
            <Popconfirm
              title="是否禁用/启用此菜单？"
              onConfirm={() => statusHandle(record)}
              okText="是"
              cancelText="否"
            >
              <a>{record.status === 0 ? '启用' : '禁用'}</a>
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <>
      <Table
        bordered
        columns={columns}
        childrenColumnName="permissions"
        dataSource={dataSource}
        // pagination={pagination}
        scroll={{ x: 800 }}
        rowKey="id"
      />

      <EditForm ref={editRef} getAll={infoUpdate} />
    </>
  );
};

const Index: React.FC = () => {
  const [tableData, setTableData] = useState<MenuAPI.DataType[]>([]);
  const [loading, setLoading] = useState<boolean>(false);
  // const [current, setCurrent] = useState<number>(1);
  // const [page, setPage] = useState<number>(10);
  // const [total, setTotal] = useState<number>(0);
  const addRef = useRef<any>(false);
  const [menus, setMenus] = useState<any>([]);

  // 新增
  const add = () => {
    addRef.current.setVis(true);
  };

  // 获取菜单列表
  const getAll = async () => {
    // const condition: MenuAPI.ConditionQuery = {
    //   pageNum: current,
    //   pageSize: page,
    // };
    setLoading(true);
    const res = await menuList();
    if (res.code === 200) {
      setTableData(res.data);
      const treeData = [{ value: 0, title: '无(若无上级选择此项)' }, ...transfromData(res.data)];
      setMenus(treeData);
      // setTotal(res.data.length);
    } else {
      message.error(res.msg);
    }
    setLoading(false);
  };

  function transfromData(data: any) {
    return data.map((item: any) => {
      const { name, id, permissions: children } = item;
      const resData = { title: name, value: id, key: id, children: children };
      if (children && children.length) {
        resData.children = transfromData(children);
      }
      return resData;
    });
  }

  // const pagination = {
  //   current: current,
  //   pageSize: page,
  //   total: total,
  //   hideOnSinglePage: false,
  //   showTotal: () => `共 ${total} 条数据`,
  //   showSizeChanger: true,
  //   showQuickJumper: true,
  //   onChange: () => {
  //     getAll();
  //   },
  // };

  useEffect(() => {
    getAll();
    // }, [current, page]);
  }, []);

  return (
    <>
      <div className={css.form}>
        <Button type="primary" onClick={add}>
          <PlusOutlined /> 新增
        </Button>
      </div>
      <Spin spinning={loading}>
        <SuperTable
          dataSource={tableData}
          // pagination={pagination}
          menus={menus}
          infoUpdate={getAll}
        />
      </Spin>

      <AddForm ref={addRef} menus={menus} getAll={getAll} />
    </>
  );
};

export default Index;
